package cn.glutnn.controller;


import cn.glutnn.entity.Result;
import cn.glutnn.entity.User;
import cn.glutnn.entity.dto.LoginDTO;
import cn.glutnn.entity.dto.RegisterDTO;
import cn.glutnn.service.UserService;
import cn.glutnn.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 用户信息(User)表控制层
 *
 * @author msh
 * @since 2024-12-09 19:55:26
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public Result<List<User>> getUserList() {
        return Result.success(userService.list());
    }

    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    @PostMapping("/register")
    public Result register(@Valid @RequestBody RegisterDTO registerDTO) {
        return userService.register(registerDTO);
    }

    // 根据id查询用户信息
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable("id")Integer id) {
        return Result.success(userService.getById(id));
    }

    // 登录后获取用户信息
    @GetMapping("/userInfo")
    public Result getUserInfo() {
        Map o = ThreadLocalUtil.get();
        if (o == null) {
            return Result.error("请先登录");
        }
        Object username = o.get("username");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return Result.success(userService.getOne(wrapper));
    }
}

